#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Initial Setup. Set up tables, all new feeds, plugins, etc.
"""
import os, imp
from sqlalchemy import *

print """
Welcome to Helios.
This will do the initial setup
"""

##Create settings database
settingsDB = create_engine('sqlite:///settings.db')
settingsDB.echo = False
settingsMetadata = MetaData(settingsDB)

##Define Settings table
settings = Table('settings',settingsMetadata,
    Column('settingID', Integer, primary_key=True),
    Column('settingName', String(200)),
    Column('settingValue', UnicodeText)
)
settingsMetadata.create_all()

##Set setupComplete value to 'False'
i = settings.insert()
i.execute(settingName='setupComplete',settingValue=u"False")

##Ask whether to use sqlite or mysql
databaseType = raw_input('Which database do you wish to use? (m)ysql or (s)qlite3? ')
if databaseType == "s": ##Sqlite3 chosen
    i = settings.insert()
    i.execute(settingName='databaseType',settingValue=u"sqlite3")
    ##Create helios database
    db = create_engine('sqlite:///data/helios.db')
    db.echo = False
    metadata = MetaData(db)
elif databaseType == "m": ##Mysql chosen
    i = settings.insert()
    i.execute(settingName='databaseType',settingValue=u"mysql")
    
    username = raw_input('Please enter username: ')
    i = settings.insert()
    i.execute(settingName='mysqlUsername',settingValue=username)
    
    password = raw_input('Please enter password: ')
    i = settings.insert()
    i.execute(settingName='mysqlPassword',settingValue=password)
    
    host = raw_input('Please enter host: ')
    i = settings.insert()
    i.execute(settingName='mysqlHost',settingValue=host)
    
    name = raw_input('Please enter database name: ')
    i = settings.insert()
    i.execute(settingName='mysqlName',settingValue=name)
    
    ##Create helios database
    db = create_engine('mysql://' + username + ':' + password + '@' + host + '/' + name)
    db.echo = False
    metadata = MetaData(db)

##Define Sources table
sources = Table('sources',metadata,
    Column('sourceID', Integer, primary_key=True),
    Column('sourceURL', String(200)),
    Column('sourceTitle', String(200)),
    Column('sourceOwner', String(200)),
    Column('sourceLink', String(200)),
    Column('sourceDescription', UnicodeText),
    Column('sourceSpecification', String(20)),
    Column('sourceUpdateInterval', Integer),
    Column('sourceLastChecked', DateTime),
    Column('sourceEtag', String(200)),
    Column('sourceLastModified', DateTime),
    Column('sourceUsability', String(1)),
    Column('sourceFavourite', String(1))
)

##Define Items table
items = Table('items',metadata,
    Column('itemID', Integer, primary_key=True),
    Column('itemGuid', String(200)),
    Column('itemTitle', String(200)),
    Column('itemBody', UnicodeText),
    Column('itemAuthor', String(200)),
    Column('itemLink', String(200)),
    Column('itemDatePublished', DateTime),
    Column('itemDateParsed', DateTime),
    Column('sources_sourceID', Integer),
    Column('itemProcessFlag', Integer)
)

##Define Tags table
tags = Table('tags',metadata,
    Column('tagID', Integer, primary_key=True),
    Column('tagName', String(200))
)

##Define source2tags table
source2tag = Table('source2tag',metadata,
    Column('tags_tagID', Integer),
    Column('source_sourceID', Integer)
)

##Define SoureTypes table
sourceTypes = Table('sourceTypes',metadata,
    Column('sourceTypeID', Integer, primary_key=True),
    Column('sourceTypeName', String(200)),
    Column('sourceTypeDescription', UnicodeText)
)

##Define Flags table
flags = Table('flags',metadata,
    Column('flagID', Integer, primary_key=True),
    Column('flagName', String(200)),
    Column('flagDescription', UnicodeText)
)

##Define proccessingModuleTypes table
proccessingModuleTypes = Table('proccessingModuleTypes',metadata,
    Column('proccessingModuleTypeID', Integer, primary_key=True),
    Column('proccessingModuleTypeName', String(200)),
    Column('proccessingModuleTypeDescription', UnicodeText)
)

##Define proccessingModules table
proccessingModules = Table('proccessingModules',metadata,
    Column('proccessingModuleID', Integer, primary_key=True),
    Column('proccessingModuleName', String(200)),
    Column('proccessingModuleDescription', UnicodeText),
    Column('proccessingModuleFileName',String(200)),
)

##Define proccessingModule2proccessingType table
proccessingModule2proccessingType = Table('proccessingModule2proccessingType',metadata,
    Column('proccessingModules_proccessingModuleID', Integer),
    Column('proccessingModuleTypes_proccessingModuleTypeID', Integer)
)
##Define sourceProccessing table
sourceProccessing = Table('sourceProccessing',metadata,
    Column('proccessingModules_proccessingModuleID', Integer),
    Column('sources_sourceID', Integer)
)

metadata.create_all() #Commit all

##Load Sources
feedFileType = raw_input("Do you want to add feeds from (o)pml or (f)lat file? ")
if feedFileType.lower() == 'f':
    import addFeedsFromList
    feedFile = raw_input("Please Provide path to sources file: ")
    addFeedsFromList.AddFeedsFromFile(feedFile)
else:
    print "Ignoring that for now"

##Setup PreProcessor plugins
    ##Ask which sources to use with it
    
##Setup Processor plugins
#Get a list of all the plugins in ./Plugins/Processors
modules = []
moduleTableDefinitions = []
for mod in os.listdir('./Plugins/Processors'):
    if ".pyc" not in mod and ".py~" not in mod and ".db" not in mod:
	modules.append(mod)
for plugin in modules:
    processor = imp.load_source(plugin.replace('.py', ''),'./Plugins/Processors/' + plugin) ##Load plugin
    module = processor.Setup() #Initialise Module
    success = module.intitialSetup()
    if success == True:
	    
	##Add the module description to Database
	i = proccessingModules.insert()
	result = i.execute(module.getModuleDescription())
	moduleID = result.last_inserted_ids()[0]
	
	moduleTableDefinitions.append(module.getLinkedDataTableDefinitions()) ##Get table definitions
	
	applyToSources = raw_input('Will this processor be applied to (a)ll, (s)ome, or (n)o sources? ')
	result = db.execute(sources.select())
	sourcesDetails = result.fetchall()
	if applyToSources.lower() == "a":  ##Apply this module to all sources
	    for source in sourcesDetails:
		i = sourceProccessing.insert()
		i.execute(proccessingModules_proccessingModuleID=moduleID,sources_sourceID=source.sourceID)
	elif applyToSources.lower() == "s": ##Ask which sources to apply to
	    for source in sourcesDetails:
		print source.sourceTitle
		applyToThis = raw_input("Apply to this source? (y/n) ")
		if applyToThis.lower() == "y":
		    i = sourceProccessing.insert()
		    i.execute(proccessingModules_proccessingModuleID=moduleID,sources_sourceID=source.sourceID)
		
##Setup PostProcessors
##Setup DataSources
##Ask whether to run feedMonitor.py